package com.gitee.cui.security.netty.securechat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 16:07
 **/
public class ServerChatHandler extends SimpleChannelInboundHandler<String> {

    static final ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 收到信息进行广播
        for (Channel channel : CHANNELS) {
            if (!channel.equals(ctx.channel())) {
                // 非本人
                ctx.writeAndFlush("[" + ctx.channel().remoteAddress() +"] " + msg + "\n");
            } else {
                // 本人
                ctx.writeAndFlush("[本人] " + msg + "\n");
            }
        }

        if ("bye".equalsIgnoreCase(msg)) {
            ctx.close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("恭喜进入安全聊天器\n");
        CHANNELS.add(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
